<template>
  <scroll-view class="flex-col page mine" scroll-y @scroll="onPageScroll">
    <view class="flex-col section" :style="{ paddingTop: navHeight + 'px' }">
      <xlm-top-nav
        :scrollTop="scrollTop"
        :leftIconColor="'#fff'"
        :titleColor="'#fff'"
        :textAlign="'center'"
        title="我的"
        :showGoBack="false"
      />
      <view class="flex-col">
        <view class="mt-17 flex-col self-stretch user-layout">
          <!-- 右上角微信用户 -->
          <view class="wechat-user-top" v-if="isLogin">
            <view class="flex-row items-center">
              <image class="wechat-avatar" :src="isLogin ? userInfo.avatar : imgUrl + 'avatar1@2x.png'" />
              <text class="wechat-name">{{ isLogin ? userInfo.nickname : '微信昵称' }}</text>
            </view>
          </view>
          
          <!-- 居中用户区域 -->
          <view class="center-user-area">
            <view class="flex-row items-center user-main">
              <!-- 运动员信息卡片 -->
              <view class="flex-col items-center athlete-card" v-if="isLogin && defaultPlayer.username">
                <image class="center-avatar" :src="defaultPlayer.avatar || imgUrl + 'avatar1@2x.png'" />
                <text class="center-name">{{ defaultPlayer.username }}</text>
                <text class="view-more" @click="viewMore">查看更多</text>
              </view>
              
              <!-- 占位卡片（未登录或没有运动员时显示） -->
              <view class="flex-col items-center athlete-card" v-else>
                <view class="placeholder-avatar">
                  <image class="placeholder-icon" :src="imgUrl + 'avatar1@2x.png'" mode="aspectFill" />
                </view>
                <text class="center-name placeholder-text">微信用户</text>
              </view>
              
              <!-- 添加运动员卡片 -->
              <view class="flex-col items-center add-athlete-card" @click="navigateTo('player')" v-if="isLogin">
                <view class="add-icon-wrapper">
                  <text class="add-icon">+</text>
                </view>
                <text class="add-text">添加运动员</text>
              </view>
              
              <!-- 切换功能（暂时注释） -->
              <!-- <view v-if="isLogin && PlayerList.length > 0" class="switch-container">
                <view class="switch-btn" @click="switchAthlete">
                  <text>切换</text>
                  <image class="switch-icon" :src="imgUrl + 'switch@2x.png'" mode="aspectFit" />
                </view>
              </view> -->
            </view>
          </view>
          
          <!-- 登录按钮 -->
          <view class="login-area" v-if="!isLogin">
            <button
              class="login-btn"
              @click="loginBefore()"
            >
              <text class="login-text">登 录</text>
            </button>
          </view>
        </view>
      </view>
    </view>
    <view class="flex-col relative list">
      <!-- <view class="flex-row justify-between items-center list-item" @click="navigateTo('player')">
        <view class="flex-row">
          <image class="shrink-0 image_8" :src="imgUrl + 'addPlayer@2x.png'" />
          <text class="ml-10 font">添加运动员</text>
        </view>
        <text class="iconfont xlmicon-arrow-right"></text>
      </view> -->
      <view
        class="flex-row justify-between items-center list-item"
        @click="navigateTo('mySchedule')"
      >
        <view class="flex-row">
          <image class="shrink-0 image_8" :src="imgUrl + 'mySchedule@2x.png'" />
          <text class="ml-10 font">我的赛程</text>
        </view>
        <text class="iconfont xlmicon-arrow-right"></text>
      </view>
      <view class="flex-row justify-between items-center list-item" @click="navigateTo('myEcoin')">
        <view class="flex-row">
          <image class="shrink-0 image_8" :src="imgUrl + 'myEcoin2@2x.png'" />
          <text class="ml-10 font">我的e币</text>
        </view>
        <text class="iconfont xlmicon-arrow-right"></text>
      </view>
      <view class="flex-row justify-between items-center list-item" @click="navigateTo('myCoupon')">
        <view class="flex-row">
          <image class="shrink-0 image_8" :src="imgUrl + 'myCoupon@2x.png'" />
          <text class="ml-10 font">我的优惠券</text>
        </view>
        <text class="iconfont xlmicon-arrow-right"></text>
      </view>
      <view
        class="flex-row justify-between items-center list-item"
        @click="navigateTo('myMessage')"
      >
        <view class="flex-row">
          <image class="shrink-0 image_8" :src="imgUrl + 'myMessage@2x.png'" />
          <text class="ml-10 font">我的消息</text>
        </view>
        <text class="iconfont xlmicon-arrow-right"></text>
      </view>
      <view
        class="flex-row justify-between items-center list-item"
        @click="navigateTo('myWebsite')"
      >
        <view class="flex-row">
          <image class="shrink-0 image_8" :src="imgUrl + 'myHomePage@2x.png'" />
          <text class="ml-10 font">我的主页</text>
        </view>
        <text class="iconfont xlmicon-arrow-right"></text>
      </view>
      <view
        class="flex-row justify-between items-center list-item"
        @click="navigateTo('PersonalCustomization')"
      >
        <view class="flex-row">
          <image class="shrink-0 image_8" :src="imgUrl + 'personalCustomization@2x.png'" />
          <text class="ml-10 font">个人定制</text>
        </view>
        <text class="iconfont xlmicon-arrow-right"></text>
      </view>
      <view class="flex-row justify-between items-center list-item" @click="navigateTo('myClub')">
        <view class="flex-row">
          <image class="shrink-0 image_8" :src="imgUrl + 'myClub@2x.png'" />
          <text class="ml-10 font">我的俱乐部</text>
        </view>
        <text class="iconfont xlmicon-arrow-right"></text>
      </view>
      <view
        class="flex-row justify-between items-center list-item"
        @click="navigateTo('couponCenter')"
      >
        <view class="flex-row">
          <image class="shrink-0 image_8" :src="imgUrl + 'myCoupon@2x.png'" />
          <text class="ml-10 font">领券中心</text>
        </view>
        <text class="iconfont xlmicon-arrow-right"></text>
      </view>
    </view>
    <button
      class="mt-24 flex-col justify-start items-center text-wrapper w-full"
      v-if="isLogin"
      @click="logout"
    >
      <text class="text">退出登录</text>
    </button>
    <view style="height: 200rpx"></view>
    <XlmExpressTabbar :current="4" />
    
    <!-- 运动员选择弹窗 -->
    <uni-popup ref="athletePopup" type="bottom" :safe-area="true">
      <view class="athlete-popup">
        <view class="popup-header">
          <text class="popup-title">选择运动员</text>
          <view class="close-btn" @click="closeAthletePopup">
            <text class="close-text">×</text>
          </view>
        </view>
        <scroll-view scroll-y class="popup-scroll">
          <view v-if="PlayerList.length === 0" class="empty-state">暂无运动员信息</view>
          <view v-else>
            <view v-for="player in PlayerList" :key="player.id" class="player-item"
              :class="{selected: defaultPlayer && defaultPlayer.id===player.id}" @click="selectPlayer(player)">
              <image :src="player.avatar || (imgUrl + 'avatar1@2x.png')" class="player-avatar" mode="aspectFill" />
              <view class="player-info">
                <text class="player-name">{{ player.username }}</text>
                <text class="player-mobile">手机号：{{ player.mobile || 'N/A' }}</text>
              </view>
              <text v-if="defaultPlayer && defaultPlayer.id===player.id" class="status-selected">已选择</text>
              <text v-else class="status">选择</text>
            </view>
          </view>
        </scroll-view>
      </view>
    </uni-popup>
  </scroll-view>
</template>
<script setup lang="ts">
  import { ref, computed } from 'vue'
  import { useOutsideAppStore } from '@/store/app'
  import { imgUrl } from '@/utils/config'
  import XlmExpressTabbar from '@/components/XlmExpressTabbar/index.vue'
  import { onShow, onLoad } from '@dcloudio/uni-app'
  import { useRequest } from '@/api'
  const { API_LOGOUT_POST,API_MEMBER_LISTATHLETE_POST } = useRequest()
  const appStore = useOutsideAppStore()
  const navHeight = computed(() => appStore.navHeight)
  const scrollTop = ref(0)
  const onPageScroll = (e) => {
    scrollTop.value = e.detail.scrollTop
  }
  const isLogin = ref(false)
  const userInfo = ref({})
  onShow(() => {
    // 每次显示页面都读取一次
    let info = uni.getStorageSync('userInfo') || null
    if (typeof info === 'string') {
      try {
        info = JSON.parse(info)
      } catch {}
    }
    userInfo.value = info
    //检测是否登录
    checkLogin()
  })
  const items = ref([1, 2, 3, 4, 5, 6])
  const PlayerList = ref([]);
  const defaultPlayer = ref({})
  const currentPlayerIndex = ref(0)
  
  // 运动员选择弹窗
  const athletePopup = ref(null)
  const navigateTo = (page) => {
    // 小程序获取当前页面路由
    const pages = getCurrentPages() // 获取当前页面栈
    const currentPage = pages[pages.length - 1] // 获取当前页面
    const currentPath = currentPage.route // 获取当前页面的路径
    console.log('currentPath>>>', currentPath)
    if (!isLogin.value) {
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }
    switch (page) {
      case 'player':
        if (currentPath !== 'pages/mine/player/index') {
          uni.navigateTo({
            url: '/pages/mine/player/index'
          })
        }
        break
      case 'mySchedule':
        if (currentPath !== 'pages/mine/mySchedule/index') {
          uni.navigateTo({
            url: '/pages/mine/mySchedule/index'
          })
        }
        break
      case 'myEcoin':
        if (currentPath !== 'pages/mine/myEcoin/index') {
          uni.navigateTo({
            url: '/pages/mine/myEcoin/index'
          })
        }
        break
      case 'myCoupon':
        if (currentPath !== 'pages/mine/myCoupon/index') {
          uni.navigateTo({
            url: '/pages/mine/myCoupon/index'
          })
        }
        break
      case 'myMessage':
        if (currentPath !== 'pages/message/index') {
          uni.navigateTo({
            url: '/pages/message/index'
          })
        }
        break
      case 'myWebsite':
        if (currentPath !== 'pages/personalHomepage/index') {
          uni.navigateTo({
            url: '/pages/personalHomepage/index'
          })
        }
        break
      case 'PersonalCustomization':
        if (currentPath !== 'pages/mine/personalCustom') {
          uni.navigateTo({
            url: '/pages/mine/personalCustom'
          })
        }
        break
      case 'myClub':
        if (currentPath !== 'pages/personalCustomization/index') {
          uni.navigateTo({
            url: '/pages/clubRanking/joinTheClub'
          })
        }
        break
      case 'couponCenter':
        if (currentPath !== 'pages/mine/couponCenter/index') {
          uni.navigateTo({
            url: '/pages/mine/couponCenter/index'
          })
        }
        break
    }
  }
  const checkLogin = () => {
    console.log('checkLogin>>>', userInfo.value)
    if (!userInfo.value || !userInfo.value.mobile) {
      //未登录
      isLogin.value = false
      console.log('未登录')
    } else {
      //已登录
      isLogin.value = true
      console.log('已登录')
      console.log('userInfo>>>', userInfo)
      getList();//获取微信用户下运动员信息
    }
  }
  const getList = async () => {
    let params = {
      page: 1,
      page_size: 10,
      lng:uni.getStorageSync('longitude'),
      lat:uni.getStorageSync('latitude')
    }
    PlayerList.value = [];
    defaultPlayer.value = {};
    try {

      const res = await API_MEMBER_LISTATHLETE_POST(params)
      console.log('getList', res)

       if (res.code === 1) {
         if (res.data.data.length > 0) {
           PlayerList.value = res.data.data;
           currentPlayerIndex.value = 0;
           defaultPlayer.value = PlayerList.value[0];
         } else {
           PlayerList.value = [];
           defaultPlayer.value = {};
           currentPlayerIndex.value = 0;
         }
         console.log('defaultPlayer.value',defaultPlayer.value);
        
      } else {
        uni.showToast({ title: res.msg, icon: 'none' })
      }
    } catch (error) {
      uni.showToast({ title: error.message, icon: 'none' })
    }
  }
  
  // 切换运动员
  const switchAthlete = () => {
    if (PlayerList.value.length === 0) {
      uni.showToast({ title: '暂无运动员信息', icon: 'none' })
      return
    }
    athletePopup.value && athletePopup.value.open()
  }
  
  // 关闭运动员选择弹窗
  const closeAthletePopup = () => {
    athletePopup.value && athletePopup.value.close()
  }
  
  // 选择运动员
  const selectPlayer = (player) => {
    defaultPlayer.value = player
    currentPlayerIndex.value = PlayerList.value.findIndex(p => p.id === player.id)
    closeAthletePopup()
    uni.showToast({ title: `已选择：${player.username}`, icon: 'success' })
  }
  
  // 查看更多 - 查看运动员详细信息
  const viewMore = () => {
    if (!isLogin.value) {
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }
    
    // 跳转到运动员信息页面
    uni.navigateTo({
      url: '/pages/mine/athleteInfo/index'
    })
  }
  
  const loginBefore = () => {
    console.log('loginBefore>>>')

    uni.navigateTo({
      url: '/pages/login/index'
    })
  }
  const logout = async () => {
    // 显示确认对话框
    uni.showModal({
      title: '确认退出',
      content: '确定要退出登录吗？',
      confirmText: '确定',
      cancelText: '取消',
      success: async (res) => {
        if (res.confirm) {
          // 用户点击确定，执行退出登录
          try {
            const logoutRes = await API_LOGOUT_POST()
            if (logoutRes.code === 1) {
              uni.removeStorageSync('userInfo')
              isLogin.value = false
              uni.showToast({
                title: '退出成功',
                icon: 'success'
              })
            } else {
              uni.showToast({ title: logoutRes.msg, icon: 'none' })
            }
          } catch (error) {
            uni.showToast({ title: error.message, icon: 'none' })
          }
        }
      }
    })
  }
</script>
<style lang="scss" scoped>
  @import './index.scss';
</style>
